#include "StdAfx.h"
#include "timer_queue_driver_impl.h"

timer_queue_driver_impl::timer_queue_driver_impl()
{
	queue_ = NULL;
}

timer_queue_driver_impl::~timer_queue_driver_impl()
{
	if( queue_ )
	{
		delete queue_;
		queue_ = NULL;
	}
}

long 
timer_queue_driver_impl::schedule_timer(aot::inet::itimer_queue_event_handler* ev, 
										const aot::inet::inet_time_t* tm, 
										bool loop/* = false*/, 
										void* act/* = NULL*/)
{
	long r = -1;
	ACE_Time_Value t(tm->sec, tm->usec);
	t += ACE_OS::gettimeofday();

	if( !loop )
	{
		r = this->queue_->schedule(ev, act, t, ACE_Time_Value::zero);
	}
	else
	{
		r = this->queue_->schedule(ev, act, t, ACE_Time_Value(tm->sec, tm->usec));
	}

	return ( r == -1 ) ? aot::inet::e_ret_failed : r;
}

bool 
timer_queue_driver_impl::cancel_all_timer(aot::inet::itimer_queue_event_handler* ev)
{
	this->queue_->cancel(ev, 1);
	return true;
}

bool 
timer_queue_driver_impl::cancel_timer(long timer_id)
{
	this->queue_->cancel(timer_id, NULL, 1);
	return true;
}

void 
timer_queue_driver_impl::calculate_timeout(aot::inet::inet_time_t* out_timeout,
										   const aot::inet::inet_time_t* max_wait_tm)
{
	ACE_Time_Value max_t(max_wait_tm->sec, max_wait_tm->usec);
	/// max_t += this->queue_->gettimeofday();

	ACE_Time_Value* v = this->queue_->calculate_timeout(&max_t);

	out_timeout->sec = v->sec();
	out_timeout->usec = v->usec();
}

int 
timer_queue_driver_impl::expire()
{
	return this->queue_->expire();
}

timer_queue_driver_impl* 
timer_queue_driver_impl::create_timer_queue_list()
{
	timer_queue_driver_impl* p = NULL;

	ACE_NEW_NORETURN( p, timer_queue_driver_impl);
	if( NULL == p)
	{
		aot_log_error(AOT_LM_ERROR, "no memory! timer_queue_driver_impl::create_timer_queue_list()");
		return NULL;
	}

	ACE_NEW_NORETURN( p->queue_, timer_queue_list);
	if( NULL == p->queue_)
	{
		aot_log_error(AOT_LM_ERROR, "no memory! timer_queue_driver_impl::create_timer_queue_list()");
		return NULL;
	}

	return p;
}

timer_queue_driver_impl* 
timer_queue_driver_impl::create_timer_queue_heap()
{
	timer_queue_driver_impl* p = NULL;

	ACE_NEW_NORETURN( p, timer_queue_driver_impl);
	if( NULL == p)
	{
		aot_log_error(AOT_LM_ERROR, "no memory! timer_queue_driver_impl::create_timer_queue_list()");
		return NULL;
	}

	ACE_NEW_NORETURN( p->queue_, timer_queue_heap);
	if( NULL == p->queue_)
	{
		aot_log_error(AOT_LM_ERROR, "no memory! timer_queue_driver_impl::create_timer_queue_list()");
		return NULL;
	}

	return p;
}